import { useState, useEffect, useCallback } from 'react';

interface KeyboardNavigationOptions {
  enableArrowKeys?: boolean;
  enableEnterKey?: boolean;
  enableEscapeKey?: boolean;
  enableTabKey?: boolean;
}

export const useKeyboardNavigation = <T,>(
  items: T[],
  options: KeyboardNavigationOptions = {}
) => {
  const {
    enableArrowKeys = true,
    enableEnterKey = true,
    enableEscapeKey = true,
    enableTabKey = true
  } = options;

  const [focusedIndex, setFocusedIndex] = useState<number>(-1);
  const [selectedItem, setSelectedItem] = useState<T | null>(null);

  const handleKeyDown = useCallback((event: KeyboardEvent) => {
    if (items.length === 0) return;

    switch (event.key) {
      case 'ArrowUp':
        if (enableArrowKeys) {
          event.preventDefault();
          setFocusedIndex(prev => 
            prev <= 0 ? items.length - 1 : prev - 1
          );
        }
        break;

      case 'ArrowDown':
        if (enableArrowKeys) {
          event.preventDefault();
          setFocusedIndex(prev => 
            prev >= items.length - 1 ? 0 : prev + 1
          );
        }
        break;

      case 'Enter':
        if (enableEnterKey && focusedIndex >= 0) {
          event.preventDefault();
          setSelectedItem(items[focusedIndex]);
        }
        break;

      case 'Escape':
        if (enableEscapeKey) {
          event.preventDefault();
          setFocusedIndex(-1);
          setSelectedItem(null);
        }
        break;

      case 'Tab':
        if (enableTabKey) {
          // Tab键的默认行为是移动焦点，我们不阻止它
          // 但可以在这里添加自定义逻辑
        }
        break;

      default:
        break;
    }
  }, [items, focusedIndex, enableArrowKeys, enableEnterKey, enableEscapeKey, enableTabKey]);

  const focusItem = useCallback((index: number) => {
    if (index >= 0 && index < items.length) {
      setFocusedIndex(index);
    }
  }, [items.length]);

  const selectItem = useCallback((index: number) => {
    if (index >= 0 && index < items.length) {
      setFocusedIndex(index);
      setSelectedItem(items[index]);
    }
  }, [items]);

  useEffect(() => {
    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [handleKeyDown]);

  return {
    focusedIndex,
    selectedItem,
    focusItem,
    selectItem,
    resetFocus: () => setFocusedIndex(-1),
    resetSelection: () => setSelectedItem(null)
  };
};